<script setup>
// @ts-ignore
import videoCover from "@/components/videoCover/index.vue";
import { getCurrentInstance, reactive, ref, watchEffect } from "vue";
import { v4 as uuidv4 } from "uuid"

// 导入视频数据
import useStore from "@/store"
import { UploadImage, UploadVideo } from "@/api/file";
import { upVideo } from '@/api/video'
import { getVideoInfo } from '@/api/video'
import { ElMessage } from "element-plus";

const { video } = useStore()
const { proxy } = getCurrentInstance()
const uploadLoading = ref(false)

// 视频裁剪参数
const videoForm = reactive({
	videoUrl: "",
	file: {},
	comIsShow: false,
});
const emits = defineEmits("uploadSuc")
// const getLoadVideoInfo = async (id) => {
// 	const res = await getVideoInfo(id)
// 	video.updateVideoInfo({
// 		id: res.id,
// 		videoUrl: undefined,
// 		description: res.description,
// 		coverUrl: res.coverUrl,
// 		title: res.title,
// 		fileRemote: res.fileRemote
// 	})
// }
// if (proxy.$route.query.id) {
// 	getLoadVideoInfo(proxy.$route.query.id)
// }


watchEffect(() => {
	if (!video.uploadVideoInfo.videoUrl) return;
	// 本地赋值裁剪文件
	getFileFromUrl(video.uploadVideoInfo.videoUrl, 'cover', 'video/mp4').then(res => {
		videoForm.file = res;
	})
	// 本地赋值视频地址
	videoForm.videoUrl = video.uploadVideoInfo.videoUrl;
})

// 将链接转换成file文件
function getFileFromUrl (url, fileName, type) {
	return new Promise((resolve, reject) => {
		var blob = null;
		var xhr = new XMLHttpRequest();
		xhr.open("GET", url);
		xhr.setRequestHeader('Accept', type);
		xhr.responseType = "blob";
		// 加载时处理
		xhr.onload = () => {
			// 获取返回结果
			blob = xhr.response;
			let file = new File([blob], fileName, { type });
			// 返回结果
			resolve(file);
		};
		xhr.onerror = (e) => {
			reject(e)
		};
		// 发送
		xhr.send();
	});
}

// 文件发生变化时改变
const fileChange = (e) => {
	let videoFile = e.target.files[0];
	if (videoFile) {
		videoForm.videoUrl = URL.createObjectURL(videoFile);
		videoForm.file = videoFile;
	}
};

// 打开组件裁剪
const shows = () => {
	videoForm.comIsShow = true;
};


//关闭裁剪组件回调
const close = () => {
	videoForm.comIsShow = false;
};

//确认封面回调 data返回值
const confirmImg = async (data) => {

	await getFileFromUrl(data.url, 'coverImage' + getRandomSixDigitFromUUID() + '.png', 'image/png').then(async res => {
		const formData = new FormData();
		formData.append('file', res)
		const result = await UploadImage(formData);
		video.uploadVideoInfo.coverUrl = result;
	})
};

function getRandomSixDigitFromUUID () {
	const uuid = uuidv4();
	const sixDigits = uuid.slice(0, 6).replace(/-/g, '');
	return parseInt(sixDigits, 16) % 1000000;
}

//提交上传信息
const submit = async () => {
	uploadLoading.value = true
	try {
		proxy.$route.query.id ? await upVideo(video.uploadVideoInfo) : await UploadVideo(video.uploadVideoInfo)
		video.updateVideoInfo({
			videoUrl: undefined,
			description: "",
			coverUrl: "",
			title: ""
		})
		// proxy.$router.push("/videoList")
		emits("uploadSuc")
		ElMessage.success(proxy.$route.query.id ? '编辑成功' : '上传成功')
	} catch (e) {
	} finally {
		uploadLoading.value = false
	}
}

</script>

<template>
	<!--总内容区域-->
	<div class="flex w-full" v-loading="uploadLoading" element-loading-text="正在上传中">
		<!--左侧信息填写区域-->
		<div class="flex-1 text-[14px] px-[20px]">
			<!--作品描述-->
			<div class="mt-[10px]">
				<div class="font-bold mb-[10px]">作品描述</div>
				<div>
					<el-input v-model="video.uploadVideoInfo.title" type="textarea" placeholder="请填写作品标题,为作品获得更多流量" :rows="1"
						maxlength="30" show-word-limit class="mb-[10px]"></el-input>
					<el-input v-model="video.uploadVideoInfo.description" type="textarea" placeholder="添加作品介绍" :rows="3"
						maxlength="1000" show-word-limit>
					</el-input>
					<div class="mt-[10px] flex tuijian text-[12px]">
						<span class="mr-[20px] text-[#25263299]">推荐</span>
						<div>
							<span v-for="item in 5" class="mr-[10px]" :key="item">测试推荐</span>
						</div>
					</div>
					<el-select v-model="video.uploadVideoInfo.type" placeholder="设置视频类型" class="mt-[10px]">
						<el-option label="公开" :value="1" />
						<el-option label="私密" :value="2" />
					</el-select>
					<el-select v-model="video.uploadVideoInfo.isTop" placeholder="是否设置置顶" class="mt-[10px]">
						<el-option label="是" :value="1" />
						<el-option label="否" :value="2" />
					</el-select>
				</div>
			</div>
			<!--封面上传-->
			<div class="mt-[20px]">
				<div class="font-bold mb-[10px]">设置封面</div>
				<el-button size="large" color="#fe3355" @click="shows" v-if="!video.uploadVideoInfo.coverUrl">
					提取封面
				</el-button>
				<div v-else class="w-[150px] h-[150px] rounded-[20px] overflow-hidden flex items-center bg-[#000]">
					<el-image :src="video.uploadVideoInfo.coverUrl" class="w-full h-auto" />
				</div>
			</div>
			<!--提交表单-->
			<div class="mt-[20px]">
				<el-button size="large" :type="proxy.$route.query.id ? 'warning' : 'primary'" @click="submit">
					{{ proxy.$route.query.id ? '确认编辑' : '提交上传' }}
				</el-button>
			</div>
		</div>
		<!--右侧预览区域-->
		<div class="w-[300px]">
			<div class="box">
				<div class="font-bold mb-[10px]">预览视频</div>
				<video class="videos" controls autoplay loop :src="videoForm.videoUrl"></video>
				<div class="btns">
					<!--<el-button size="large" class="button">-->
					<!--  选择视频文件-->
					<!--  <input-->
					<!--      type="file"-->
					<!--      id="video-file"-->
					<!--      accept="video/*"-->
					<!--      @change="fileChange"-->
					<!--  />-->
					<!--</el-button>-->
				</div>
			</div>
		</div>
	</div>
	<!--设置封面弹层-->
	<videoCover :isShow="videoForm.comIsShow" :file="videoForm.file" @closeDialog="close" @confirmImg="confirmImg">
	</videoCover>
</template>

<style scoped lang="scss">
.tuijian {
	border: 1px solid #ccc;
	padding: 5px;
	border-radius: 5px;
}

.button {
	position: relative;
}

.button input {
	position: absolute;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	opacity: 0;
	cursor: pointer;
}

.box {
	h1 {
		font-size: 40px;
		text-align: center;
		margin-bottom: 50px;
		color: #fe3355;
		font-weight: normal;
		margin-top: 60px;
	}

	.videos {
		width: 100%;
		height: 500px;
		margin: 0 auto;
		display: block;
		background-color: #000;
	}

	.btns {
		display: flex;
		align-items: center;
		justify-content: center;
		margin-top: 50px;
	}
}

.look_img {
	display: flex;
	align-items: center;
	justify-content: center;
	margin-top: 50px;

	img {
		width: auto;
		height: 200px;
	}
}
</style>
